package com.example.mptnet;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.app.AppCompatDelegate;
import androidx.core.content.ContextCompat;

import com.example.mptnet.Interfaces.API;
import com.example.mptnet.Models.Users_info;

import java.util.ArrayList;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class MainActivity extends AppCompatActivity {
    SharedPreferences settings;
    SharedPreferences.Editor edit;
    EditText login,password;
    ArrayList<Users_info> Users;
    API api;
    Retrofit retrofit;
    String theme;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView text = findViewById(R.id.textView);
        settings = getSharedPreferences("SETTINGS", MODE_PRIVATE);
        edit = settings.edit();
        theme = settings.getString("theme","night");
        edit.putString("theme","night");
        if(theme.equals("light"))
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        else
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES)
            getWindow().getDecorView().setBackground(ContextCompat.getDrawable(MainActivity.this,R.drawable.i));
        else
            getWindow().getDecorView().setBackground(ContextCompat.getDrawable(MainActivity.this,R.drawable.ii));
        text.setText(Html.fromHtml("Для авторизации используйте логин и пароль, который вы можете зарегать в боте <a href='https://t.me/zakazcsBot'>@ZakazcsBot</a>", Html.FROM_HTML_MODE_COMPACT));
        text.setClickable(true);
        text.setMovementMethod(LinkMovementMethod.getInstance());
        if(settings.contains("UID")) {
            startActivity(new Intent(MainActivity.this, UserWindow.class));
            finish();
        }
        else {
            Users = new ArrayList<Users_info>();
            retrofit = Builder.request();
            login = findViewById(R.id.login);
            password = findViewById(R.id.password);
            api = retrofit.create(API.class);
            Call<ArrayList<Users_info>> callUsers = api.GetInfo();
            callUsers.enqueue(new Callback<ArrayList<Users_info>>() {
                @Override
                public void onResponse(Call<ArrayList<Users_info>> call, Response<ArrayList<Users_info>> response) {
                    if (response.isSuccessful())
                        Users = response.body();
                }

                @Override
                public void onFailure(Call<ArrayList<Users_info>> call, Throwable t) {
                    Log.e("Ошибочка", t.getMessage());
                    Toast.makeText(MainActivity.this,t.getMessage(), Toast.LENGTH_LONG).show();
                }
            });
            findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    String Login = login.getText().toString();
                    String Password = password.getText().toString();
                    if (Login.isEmpty()) login.setError("Поле не должно быть пустым");
                    else if (Password.isEmpty()) password.setError("Поле не должно быть пустым");
                    else if (Login.length() < 5)
                        login.setError("Поле должно иметь больше 4 символов");
                    else if (Password.length() < 7)
                        password.setError("Поле должно иметь больше 6 символов");
                    else if (!CheckInArray(Login, Password)) {
                        login.setError("Неверный логин или пароль");
                        password.setError("Неверный логин или пароль");
                    } else if (CheckInArray(Login, Password)) {
                        edit.putString("login", Login);
                        edit.putString("password", Password);
                        edit.putString("UID", GetUID(Login, Password));
                        edit.commit();
                        startActivity(new Intent(MainActivity.this, UserWindow.class));
                        finish();
                    }
                }
            });

        }
    }
    boolean CheckInArray(String login, String password){
        for (Users_info us: this.Users) {
            if(us.Auth(login, password))
                return true;
        }
        return false;
    }
    String GetUID(String login, String password){
        for (Users_info us: this.Users)
            if(us.Auth(login, password))
                return us.getUser_id();
        return "";
    }
}